import { IBlobResponse } from "@/api/dxn/type"
import http, { httpB } from "@/api/helper/request"
import { Toast } from "@/components/messages"
// import { useLocale } from "@/locales"
// import { Toast } from "@/components/messages"

// 导出文件函数，接收接口 URL、文件名和接口参数
export const exportFileFromApi = async (
	apiUrl: string,
	fileName: string,
	params: Record<string, any> = {},
	fileType: string = "application/vnd.ms-excel"
) => {
	// const { formatMessage } = useLocale()
	try {
		// 从接口获取数据，带上参数
		const ret = await http.post<Blob>(apiUrl, params, { responseType: "blob" })
		console.log(ret)
		const [err, response] = ret
		if (err) {
			if ((err as any).msg === "SUCCESS") return true
			else if ((err as any).msg) {
				Toast.error((err as any).msg)
			}
		}
		if (err instanceof Blob) {
			// if (err.size < 100) {
			// 	return Toast.error(formatMessage({ id: "common.export_err" }))
			// } else {
			// 	Toast.error(formatMessage({ id: "common.export_success" }))
			// }
			if (err.size < 100) return
			const blob = new Blob([err], { type: fileType })
			const url = URL.createObjectURL(blob)
			const link: any = document.createElement("a")
			link.href = url
			link.download = fileName
			// 触发下载
			document.body.appendChild(link) // 需要将 <a> 元素添加到 DOM 中才能触发点击
			link.click()
			// 清理资源
			document.body.removeChild(link)
			URL.revokeObjectURL(url)
			console.log(response, "response", err)
		}
		// 创建 Blob 对象
	} catch (error) {
		console.error("Error fetching data from API:", error)
	}
}
export const exportFileFromApiB = async (
	apiUrl: string,
	fileName: string,
	params: Record<string, any> = {},
	fileType: string = "application/vnd.ms-excel"
) => {
	// const { formatMessage } = useLocale()
	try {
		// 从接口获取数据，带上参数
		const [err, response] = await httpB.post<Blob>(apiUrl, params, { responseType: "blob" })
		if (err instanceof Blob) {
			// if (err.size < 100) {
			// 	return Toast.error(formatMessage({ id: "common.export_err" }))
			// } else {
			// 	Toast.error(formatMessage({ id: "common.export_success" }))
			// }
			if (err.size < 100) return
			const blob = new Blob([err], { type: fileType })
			const url = URL.createObjectURL(blob)
			const link: any = document.createElement("a")
			link.href = url
			link.download = fileName
			// 触发下载
			document.body.appendChild(link) // 需要将 <a> 元素添加到 DOM 中才能触发点击
			link.click()
			// 清理资源
			document.body.removeChild(link)
			URL.revokeObjectURL(url)
			console.log(response, "response", err)
		}
		// 创建 Blob 对象
		if (err) {
			if ((err as any).msg === "SUCCESS") return true
			else if ((err as any).msg) {
				Toast.error((err as any).msg)
			}
		}
	} catch (error) {
		console.error("Error fetching data from API:", error)
	}
}

const getFileNameExport = (res: IBlobResponse) => {
	const disposition = res.headers["content-disposition"]
	const fileNames = disposition && disposition.split("''")
	let fileName = Array.isArray(fileNames) && fileNames.length && fileNames[1]
	fileName = decodeURIComponent(fileName)

	return fileName
}

export const exportFileFromApiHaveName = async (
	apiUrl: string,
	params: Record<string, any> = {},
	formatMessage?: Function,
	config: object = {},
	fileType: string = "application/vnd.ms-excel"
) => {
	try {
		const [err, response] = await http.post(apiUrl, params, { responseType: "blob", timeout: 1000 * 60, ...config })
		if (err && err.msg) {
			Toast.warning(err.msg)
		}
		if (err instanceof Blob) {
			if (err.size < 100) return

			const blob = new Blob([err], { type: fileType })
			const url = URL.createObjectURL(blob)
			const link: any = document.createElement("a")
			link.href = url
			link.download = getFileNameExport(response as IBlobResponse)
			document.body.appendChild(link)
			link.click()
			document.body.removeChild(link)
			URL.revokeObjectURL(url)

			if (formatMessage) Toast.info(formatMessage({ id: "common.export_success" }))

			return true
		}

		if (err.message && err?.message.indexOf("timeout") !== -1 && formatMessage) {
			Toast.error(formatMessage({ id: "response.timeout" }))
		}
	} catch (error) {
		return false
	}
}

export const exportFileFromApiBHaveName = async (
	apiUrl: string,
	params: Record<string, any> = {},
	formatMessage?: Function,
	config: object = {},
	fileType: string = "application/vnd.ms-excel"
) => {
	try {
		const [err, response] = await httpB.post(apiUrl, params, { responseType: "blob", ...config })
		if (err instanceof Blob) {
			if (err.size < 100) return

			const blob = new Blob([err], { type: fileType })
			const url = URL.createObjectURL(blob)
			const link: any = document.createElement("a")
			link.href = url
			link.download = getFileNameExport(response as IBlobResponse)
			document.body.appendChild(link)
			link.click()
			document.body.removeChild(link)
			URL.revokeObjectURL(url)

			if (formatMessage) Toast.info(formatMessage({ id: "common.export_success" }))

			return true
		}

		if (err.message && err?.message.indexOf("timeout") !== -1 && formatMessage) {
			Toast.error(formatMessage({ id: "response.timeout" }))
		}
	} catch (error) {
		return false
	}
}

export const exportFileFromApiBHaveNameMethodGet = async (
	apiUrl: string,
	params: Record<string, any> = {},
	formatMessage?: Function,
	fileType: string = "application/vnd.ms-excel"
) => {
	try {
		const [err, response] = await httpB.get(apiUrl, params, { responseType: "blob" })
		if (err && err.msg) {
			Toast.warning(err.msg)
		}
		if (err instanceof Blob) {
			if (err.size < 100) return

			const blob = new Blob([err], { type: fileType })
			const url = URL.createObjectURL(blob)
			const link: any = document.createElement("a")
			link.href = url
			link.download = getFileNameExport(response as IBlobResponse)
			document.body.appendChild(link)
			link.click()
			document.body.removeChild(link)
			URL.revokeObjectURL(url)

			if (formatMessage) Toast.info(formatMessage({ id: "common.export_success" }))

			return true
		}

		if (err.message && err?.message.indexOf("timeout") !== -1 && formatMessage) {
			Toast.error(formatMessage({ id: "response.timeout" }))
		}
	} catch (error) {
		return false
	}
}
